package com.example.c94s3plyhyfc.web;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Hashtable;

@Component
@ServerEndpoint(value = "/websocket/{id}")
public class SessionServer {

    // 必须用静态
    private static Hashtable<String,Session> webSocketMap = new Hashtable<>();

    // 连接建立成功调用的方法
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) {
        //将id存入会话
        session.getUserProperties().put("id",id);
        webSocketMap.put(id, session);
    }

    // 连接关闭调用的方法
    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(session.getUserProperties().get("id"));
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println(message);
        System.out.println(session);
        System.out.println(webSocketMap);
        // 解析消息 ;  id:msg
        String[] items = message.split(":");
        String id = items[0];
        String msg = items[1];
        // 查找接受者会话对象
        Session session1 = webSocketMap.get(id);
        // 发送消息给接受者
        session1.getBasicRemote().sendText(message);
    }

    @Scheduled(cron="*/10 * * * * ?")
    public void sendSystemMsg() throws IOException {
        for(Session s : webSocketMap.values()){
            s.getBasicRemote().sendText("系统消息: 快下课!");
        }
    }


}
